package com.dituhui.web.util;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.dituhui.tool.io.Constants;
import com.dituhui.tool.io.FileTool;
import com.dituhui.tool.util.StringUtil;
import com.dituhui.web.vo.UserInfo;

import net.sf.json.JSONObject;

/**
 * 用户信息读取工具
 * 
 * @author liweigu
 *
 */
public class UserInfoUtil {
	private static final String userInfoFilePath = Constants.getValue("userInfoFilePath", "web_config.properties");
	private static final String groupFilePath = Constants.getValue("groupFilePath", "web_config.properties");

	/**
	 * 读取用户信息列表
	 * 
	 * @return 用户信息列表
	 */
	public static List<UserInfo> getUserInfos() {
		List<UserInfo> userInfos = new ArrayList<UserInfo>();

		if (userInfoFilePath != null && userInfoFilePath.length() > 0) {
			ArrayList<String> lines = FileTool.readFile(new File(userInfoFilePath));
			for (String line : lines) {
				if (line.length() == 0 || line.startsWith(StringUtil.PoundSign)) {
					// 跳过空行和注释行
					continue;
				}
				if (line.contains(StringUtil.DoubleUnderline)) {
					String[] arr = line.split(StringUtil.DoubleUnderline);
					UserInfo userInfo = new UserInfo();
					userInfo.setPhone(arr[0]);
					userInfo.setName(arr[1]);
					userInfo.setRights(arr[2]);
					userInfo.setRegionDataset(arr[3]);
					userInfos.add(userInfo);
				}
			}
		}

		return userInfos;
	}

	/**
	 * 根据手机号获取用户信息
	 * 
	 * @param phone 手机号
	 * @return 用户信息
	 */
	public static UserInfo getUserInfoByPhone(String phone) {
		UserInfo resultUserInfo = null;

		List<UserInfo> userInfos = getUserInfos();
		for (UserInfo userInfo : userInfos) {
			if (phone.equals(userInfo.getPhone())) {
				resultUserInfo = userInfo;
				break;
			}
		}

		return resultUserInfo;
	}

	public static List<String> getGroups() {
		List<String> groups = null;

		if (groupFilePath != null && groupFilePath.length() > 0) {
			groups = FileTool.readFile(new File(groupFilePath));
		} else {
			groups = new ArrayList<String>();
		}

		return groups;
	}

	public static List<String> getGroupIds() {
		List<String> groupIds = new ArrayList<String>();

		List<String> groups = getGroups();
		for (String group : groups) {
			if (group != null && group.length() > 0) {
				JSONObject jsonObject = JSONObject.fromObject(group);
				JSONObject groupJSON = jsonObject.getJSONObject("group");
				String groupId = groupJSON.getString("uuid");
				groupIds.add(groupId);
			}
		}

		return groupIds;
	}

	public static boolean isGroupIdValid(String groupId) {
		if (groupId == null || groupId.length() != 32) {
			return false;
		}
		List<String> groupIds = getGroupIds();
		// if (groupIds == null) {
		// LOGGER.info("groupIds is null");
		// } else {
		// for (String s : groupIds) {
		// LOGGER.info("groupId:" + s);
		// }
		// }
		return groupIds.contains(groupId);
	}

}
